import { CloseOutlined, DeleteOutlined, PaperClipOutlined } from "@ant-design/icons"
import { Button, Card, Input, Form, Checkbox, Row, Col, Select, List } from "antd"
import React, { useCallback, useEffect, useRef, useState } from "react"

import { AsyncModal, ModalCustom, ModalRef } from "../modal.context"
import eventBus from "@/utils/event.bus"
import FormUploads from "@/components/form/form.uploads"
import FormEditor from "@/components/form/form.editor"
import "./addTradeInfo.modal.less"
import RelatProductModal from "./relatProduct.modal"
import serviceData from "@/services/service.data"
import checkImage from "@/utils/checkImage.func"
import configUrl from "@/../config/proxy"
import urlFunc from "@/utils/url.func"
import { ProductItem } from "@/interfaces/api.interface"
const { Option } = Select
interface Props {
	id?: string
	item?: {}
}
const UpdateTradeModal: React.FC<Props & ModalRef> = props => {
	const { modalRef } = props
	const { TextArea } = Input
	const [form] = Form.useForm()
	const [done, setDone] = useState(false)

	//!!!!
	let [relateProducts, setRelateProducts] = useState([])
	const closeModal = useCallback(() => {
		modalRef.current.destroy()
	}, [])
	const formatFile = (url: any) => {
		if (url instanceof Array) {
			const arr: { filePreviewUrl: string; fileSaveUrl: string; fileSize: number }[] = []
			url.forEach(item => {
				arr.push({
					filePreviewUrl: `${urlFunc.replaceUrl(item.url, "imageUrl")}`,
					fileSaveUrl: item.url,
					fileSize: 10
				})
			})
			return arr
		} else {
			return [
				{
					filePreviewUrl: `${urlFunc.replaceUrl(url, "imageUrl")}`,
					fileSaveUrl: url,
					fileSize: 10
				}
			]
		}
	}
	const [tradeClassOne, setTradeClassOne] = useState([])
	const [tradeClassTwo, setTradeClassTwo] = useState([])
	// 初始加载获取一级分类
	// useEffect(() => {
	// 	serviceData.getTradeClass({ pid: 0 }).then(res => {
	// 		setTradeClassOne(res.data)
	// 	})
	// }, [])
	// 改变一级分类加载二级分类
	const onValuesChange = useCallback((changedValues: any, values: any) => {
		if ("industryId" in changedValues) {
			serviceData.getTradeClass({ pid: changedValues.industryId }).then(res => {
				setTradeClassTwo(res.data)
			})
		}
	}, [])
	const onFinish = useCallback(
		data => {
			const productIds: any[] = []
			relateProducts.forEach(item => {
				productIds.push(item.id)
			})

			serviceData
				.updateTradeData({
					id: props.id,
					industryId: data.industryId,
					solutionId: data.solutionId,
					title: data.title,
					content: data.content,
					products: productIds,
					image: data.image?.[0].fileSaveUrl,
					introduction: data.introduction
				})
				.then(res => {
					if (res.code === 200) {
						eventBus.emit("doTradeInfo")
						closeModal()
					}
				})
		},
		[relateProducts]
	)
	const [infoData, setInfoData] = useState<any>()
	useEffect(() => {
		serviceData.getTradeDataById({ id: props.id }).then(res => {
			if (res.code === 200) {
				setRelateProducts(res.data.products)
				form.setFieldsValue({
					...res.data,
					image: !!res.data.image ? formatFile(res.data.image) : null
				})
				setDone(true)
				setInfoData(res.data)
			}
		})
	}, [props.id])
	useEffect(() => {
		serviceData.getTradeClass({ pid: 0 }).then(res => {
			setTradeClassOne(res.data)
		})
		eventBus.on("RelateProducts", val => {
			// isDefaultpic.current = false
			// setFodderPicData(val)
			// console.log(val)
			setRelateProducts(val)
		})

		return () => {
			eventBus.off("RelateProducts")
		}
	}, [])
	const relatProductsBtn = (data: any) => async () => {
		const modalData = await AsyncModal({
			content: RelatProductModal,
			mask: true,
			params: {
				data
			}
		})
		setRelateProducts(modalData)
	}
	const deleterelateProduct = (id: number) => () => {
		setRelateProducts(
			relateProducts.filter(item => {
				return item.id !== id
			})
		)
	}
	return (
		done && (
			<Card
				id="tradeInfoBox"
				style={{ width: 700 }}
				title={props.id == "" ? "新增行业信息" : "编辑行业信息"}
				extra={
					<Button type="text" onClick={closeModal}>
						<CloseOutlined />
					</Button>
				}
			>
				<div className="productInfo">
					<div className="productInfoForm">
						<Form
							layout="horizontal"
							labelCol={{ span: 6 }}
							// wrapperCol={{ span: 19 }}
							form={form}
							preserve={false}
							onFinish={onFinish}
							onValuesChange={onValuesChange}
							// initialValues={{ industryId: props.item.industryName }}
						>
							<Form.Item label="行业大类：" name="industryId" rules={[{ required: true, message: "请选择行业大类" }]}>
								<Select placeholder={"一级分类"}>
									{/* defaultValue={props.item.industryName} */}
									{tradeClassOne.map(item => (
										<Option key={item.id} value={item.id}>
											{item.title}
										</Option>
									))}
								</Select>
							</Form.Item>
							<Form.Item
								label="应用场景/解决方案："
								name="solutionId"
								rules={[{ required: true, message: "请选择应用场景/解决方案" }]}
							>
								<Select placeholder={"请选择应用场景/解决方案"}>
									{tradeClassTwo.map(item => (
										<Option key={item.id} value={item.id}>
											{item.title}
										</Option>
									))}
								</Select>
							</Form.Item>
							<Form.Item
								label="方案/技术应用命名："
								name="title"
								rules={[{ required: true, message: "请选择方案/技术应用命名" }]}
							>
								{/* <Select placeholder={"请选择方案/技术应用命名"}>
								{tradeThree.map(item => (
									<Option key={item.id} value={item.id}>
									</Option>
								))}
							</Select> */}
								<Input placeholder="请输入方案/技术应用命名" />
							</Form.Item>
							<Form.Item
								label="封面图："
								name="image"
								rules={[{ required: true, message: "请选择封面图" }]}
								extra="文件大小2M之内，分辨率796*448jpg、png"
							>
								<FormUploads
									accept=".png, .jpg, .jpeg"
									customCheck={checkImage("image", 2)}
									checkType={"hotImage"}
									imgAction={{ crop: true, aspectRatio: [796, 448] }}
								></FormUploads>
							</Form.Item>
							<Form.Item label="方案简介：" name="introduction">
								<TextArea showCount maxLength={150} />
							</Form.Item>
							<Form.Item label="具体内容：" name="content">
								<FormEditor defaultContent={infoData?.content} />
								{/* defaultContent={infoData.content} */}
							</Form.Item>
							<Form.Item label="关联产品：">
								<Button onClick={relatProductsBtn(relateProducts)}>{"+添加"}</Button>
								{!!relateProducts && (
									<List
										grid={{ gutter: 16, column: 2 }}
										dataSource={relateProducts}
										renderItem={item => (
											<List.Item>
												<div style={{ margin: "10px 0" }}>
													<PaperClipOutlined style={{ marginRight: "5px" }} />
													<span>{item.title}</span>
													<DeleteOutlined style={{ marginLeft: "10px" }} onClick={deleterelateProduct(item.id)} />
												</div>
											</List.Item>
										)}
									/>
								)}
							</Form.Item>

							<Form.Item style={{ textAlign: "right" }}>
								<Button type="primary" htmlType="submit">
									保存
								</Button>
								<Button style={{ marginLeft: 10 }} htmlType="button" onClick={closeModal}>
									取消
								</Button>
							</Form.Item>
						</Form>
					</div>
				</div>
			</Card>
		)
	)
}

export default UpdateTradeModal
